package com.ruoyi.web.controller.ability;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import com.ruoyi.common.AES128Util;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.QRCodeUtils;
import com.ruoyi.system.domain.Banner;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Qrcode;
import com.ruoyi.system.service.IQrcodeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 二维码Controller
 *
 * @author ruoyi
 * @date 2025-05-07
 */
@RestController
@RequestMapping("/system/qrcode")
public class QrcodeController extends BaseController {
    @Autowired
    private IQrcodeService qrcodeService;

    @Autowired
    private RuoYiConfig ruoYiConfig;

    /**
     * 查询二维码列表
     */
    @PreAuthorize("@ss.hasPermi('system:qrcode:list')")
    @GetMapping("/list")
    public TableDataInfo list(Qrcode qrcode) {
        startPage();
        List<Qrcode> list = qrcodeService.selectQrcodeList(qrcode);
        return getDataTable(list);
    }

//    /**
//     * 导出二维码列表
//     */
//    @PreAuthorize("@ss.hasPermi('system:qrcode:export')")
//    @Log(title = "二维码", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, Qrcode qrcode)
//    {
//        List<Qrcode> list = qrcodeService.selectQrcodeList(qrcode);
//        ExcelUtil<Qrcode> util = new ExcelUtil<Qrcode>(Qrcode.class);
//        util.exportExcel(response, list, "二维码数据");
//    }

    private static final Float WIDTH_IMAGE = 200f;
    private static final Float HEIGHT_IMAGE = 200f;

    private static final Integer WIDTH_PDF = 200;
    private static final Integer HEIGHT_PDF = 200;

    private static final BaseColor NORMAL_COLOR = BaseColor.WHITE;
    private static final BaseColor PRINT_COLOR = BaseColor.RED;

    /**
     * 导出二维码列表
     */
    // @PreAuthorize("@ss.hasPermi('system:qrcode:export')")
    @Log(title = "二维码", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void print(Qrcode qrcode, HttpServletResponse response) throws Exception {
        if (qrcode == null)
            qrcode = new Qrcode();
        // 创建输出流
        OutputStream outputStream = response.getOutputStream();

        RuoYiConfig.Minio minio = ruoYiConfig.getMinio();


        List<Qrcode> qrcodeList = new ArrayList<>();
        if (qrcode.getPrintId() != null) {
            Qrcode qcd = qrcodeService.selectQrcodeByQrcodeId(qrcode.getPrintId());
            qrcodeList.add(qcd);
        } else {
            if (qrcode.getIds() != null && qrcode.getIds().size() > 0) {
                for (int i = 0; i < qrcode.getIds().size(); i++) {
                    Long tmpId = qrcode.getIds().get(i);
                    Qrcode qcd = qrcodeService.selectQrcodeByQrcodeId(tmpId);
                    qrcodeList.add(qcd);
                }
            } else {
                qrcodeList = qrcodeService.selectQrcodeList(qrcode);
            }

        }

        Document document = new Document();
        Rectangle pageSize = new Rectangle(WIDTH_PDF, HEIGHT_PDF);
//        int print = 0;
//        if(qrcodeList.size()>0){
//           print = qrcodeList.get(0).getPrint();
//        }
//        if (print == 1) {
//            pageSize.setBackgroundColor(PRINT_COLOR);
//        } else {
//            pageSize.setBackgroundColor(NORMAL_COLOR);
//        }
        // pageSize.setBackgroundColor(BaseColor.PINK);
        document.setPageSize(pageSize);
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        document.open();
        Qrcode qrcodeUp = null;
        //   String miniUrl = String.format("%s%s",minio.getStaticImageServer(),"mini_qr@x2.jpg");
        Image miniProgramImage = null;
        if(qrcode.getQrcodeTemplate()==null){
            qrcode.setQrcodeTemplate(2);
        }
        for (int i = 0; i < qrcodeList.size(); i++) {
            Qrcode tmp = qrcodeList.get(i);
            Image logoImage = null;
            long qid = tmp.getQrcodeId();
            String hex = AES128Util.getAESEncodeHex(qid + "");
            BufferedImage bufferedImage = QRCodeUtils.getQRCodeImage(hex, QRCodeUtils.DEFAULT_QRCODE_WIDTH, QRCodeUtils.DEFAULT_QRCODE_HEIGHT, tmp.getPrint() == 1);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            //将PDF的每一页渲染成一张图片;
            ImageIO.write(bufferedImage, "png", output);
            logoImage = Image.getInstance(output.toByteArray());
            switch (qrcode.getQrcodeTemplate()) {
                case 2:
                    //单布局
                    //根据域的大小缩放图片
                    logoImage.scaleToFit(WIDTH_IMAGE, HEIGHT_IMAGE);
                    logoImage.setAlignment(Image.ALIGN_CENTER);
                    //logoImage.setAbsolutePosition(0.25f, 0.2f);
                    logoImage.setAbsolutePosition(0, 0);
                    document.add(logoImage);
                    break;
                default:
                    if (miniProgramImage == null) {
                        String miniUrl = String.format("%s%s", minio.getStaticImageServer(), "jpsm/static/mini_qr@x2.jpg");
                        miniProgramImage = Image.getInstance(miniUrl);
                    }
                    float doubWidth = WIDTH_PDF/2;
                    //float doubHeight = HEIGHT_IMAGE/2;
                    //双布局
                    logoImage.scaleToFit(doubWidth,HEIGHT_PDF);
                    logoImage.setAlignment(Image.ALIGN_LEFT);
                    //logoImage.setAbsolutePosition(0.25f, 0.2f);
                    logoImage.setAbsolutePosition(0, 50);
                    document.add(logoImage);

                    miniProgramImage.scaleToFit(doubWidth, HEIGHT_PDF);
                     miniProgramImage.setAlignment(Image.ALIGN_RIGHT);
                    //logoImage.setAbsolutePosition(0.25f, 0.2f);
                    miniProgramImage.setAbsolutePosition(doubWidth, 40);
                    document.add(miniProgramImage);

                    break;
            }
            qrcodeUp = new Qrcode();
            qrcodeUp.setQrcodeId(tmp.getQrcodeId());
            qrcodeUp.setPrint(1);
            qrcodeService.updateQrcode(qrcodeUp);
            //重新开一页面
            if (i < qrcodeList.size() - 1) {
                document.newPage();
            }
        }

        // 设置响应头，控制浏览器下载该文件
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(DateUtils.dateTimeInCN() + "_qrcode.pdf", "UTF-8"));
        // response.setCharacterEncoding("utf-8");
        response.setContentType("application/pdf");
        document.close();
        writer.close();
        response.flushBuffer();
    }

    /**
     * 获取二维码详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:qrcode:query')")
    @GetMapping(value = "/{qrcodeId}")
    public AjaxResult getInfo(@PathVariable("qrcodeId") Long qrcodeId) {
        return success(qrcodeService.selectQrcodeByQrcodeId(qrcodeId));
    }

    /**
     * 新增二维码
     */
    @PreAuthorize("@ss.hasPermi('system:qrcode:add')")
    @Log(title = "二维码", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Qrcode qrcode) {
        if (qrcode.getNum() == null || qrcode.getNum() > 50) {
            return AjaxResult.error("生成数量必须大于0 小于50");
        }
        if (qrcode.getScore() == null || qrcode.getScore() < 0) {
            return AjaxResult.error("分数必须大于等于0");
        }
        return toAjax(qrcodeService.insertQrcode(qrcode));
    }

    /**
     * 修改二维码
     */
    @PreAuthorize("@ss.hasPermi('system:qrcode:edit')")
    @Log(title = "二维码", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Qrcode qrcode) {
        return toAjax(qrcodeService.updateQrcode(qrcode));
    }

    /**
     * 删除二维码
     */
    @PreAuthorize("@ss.hasPermi('system:qrcode:remove')")
    @Log(title = "二维码", businessType = BusinessType.DELETE)
    @DeleteMapping("/{qrcodeIds}")
    public AjaxResult remove(@PathVariable Long[] qrcodeIds) {
        return toAjax(qrcodeService.deleteQrcodeByQrcodeIds(qrcodeIds));
    }
}
